<template>
  <div class="container">
    <div class="app-container">
      <el-button
        type="primary"
        size="small"
        style="margin-bottom: 10px"
        @click="showAddDialog(1, { id: 0, children: permissionData })"
        >添加权限</el-button
      >
      <el-table
        :row-style="{ height: '64px' }"
        :header-cell-style="{ backgroundColor: '#f5f6f8' }"
        border
        :data="permissionData"
        row-key="id"
        default-expand-all
      >
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="标识" prop="code"></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column prop="prop" label="操作">
          <template slot-scope="{ row }">
            <el-button
              v-if="row.type === 1"
              type="text"
              size="medium"
              @click="showAddDialog(2, row)"
              >添加</el-button
            >
            <el-button type="text" size="medium" @click="showEditDialog(row)">编辑</el-button>
            <el-button type="text" size="medium" @click="deletePermission(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="45%"
        @close="$refs.form.resetFields()"
      >
        <el-form ref="form" :model="permissionForm" :rules="permissionRules" label-width="80px">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="permissionForm.name"></el-input>
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="permissionForm.code"></el-input>
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="permissionForm.description" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="开启">
            <el-switch
              v-model="permissionForm.enVisible"
              active-color="#13ce66"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="6">
                <el-button
                  type="primary"
                  size="small"
                  @click="title === '新增权限点' ? addPermission() : editPermission()"
                  >确 定</el-button
                >
                <el-button
                  @click="
                    dialogVisible = false
                    $refs.form.resetFields()
                  "
                  size="small"
                  >取 消</el-button
                >
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getPermissionListService,
  addPermissionService,
  updatePermissionService,
  deletePermissionService
} from '@/api/permission.js'
import { transListToTreeData } from '@/utils/index.js'
export default {
  name: 'Permission',
  created() {
    this.getPermissionList()
  },
  data() {
    return {
      permissionData: [], // 表格树形数据
      list: [],
      title: '', // 对话框标题
      dialogVisible: false,
      permissionForm: {
        name: '',
        code: '',
        description: '',
        type: null,
        pid: null,
        enVisible: 1
      },
      //校验规则
      permissionRules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              let children
              if (this.permissionForm.id) {
                // 编辑模式
                children = this.permissionForm.children ? this.permissionForm.children : []
                // console.log(this.permissionForm.children);
                children = children.filter((item) => item.id !== this.permissionForm.id) // 校验时去掉自己
              } else children = this.permissionForm.row.children || []
              if (children.some((item) => item.name === value)) {
                callback(new Error('该权限名称已存在'))
              } else callback()
            }
          }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              let list = this.list
              if (this.permissionForm.id) {
                // 编辑模式下
                list = this.list.filter((item) => item.id !== this.permissionForm.id) // 校验时去掉自己
              }
              if (list.some((item) => item.code === value)) {
                callback(new Error('权限标识已存在'))
              } else callback()
            }
          }
        ]
      }
    }
  },
  methods: {
    async getPermissionList() {
      const res = await getPermissionListService()
      this.list = res.data
      this.permissionData = transListToTreeData(res.data, 0) // 将列表数据转化成树形数据
    },
    // 显示添加权限点对话框
    showAddDialog(type, row) {
      //虽然可以通过重新赋值来清空表单数据，但是校验结果并不会清空，所以需要另外重置表单
      this.permissionForm = {
        name: '',
        code: '',
        description: '',
        type: null,
        pid: null,
        enVisible: 1
      }
      this.title = '新增权限点'
      this.permissionForm.pid = row.id
      this.permissionForm.type = type
      // 添加一项属性，用来校验
      this.permissionForm.row = row
      this.dialogVisible = true
    },
    // 显示编辑权限点对话框
    showEditDialog(row) {
      this.title = '修改权限点'
      this.dialogVisible = true
      // 运用展开运算符进行浅拷贝，防止修改原数据
      this.permissionForm = { ...row }
      console.log(this.permissionForm)
    },
    //新增权限点
    addPermission() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          await addPermissionService(this.permissionForm)
          this.$refs.form.resetFields()
          this.$message.success('新增权限点成功')
          this.getPermissionList()
          this.dialogVisible = false
        }
      })
    },
    // 删除权限点
    deletePermission(id) {
      this.$confirm('确认删除该条数据吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await deletePermissionService(id)
          this.$message.success('删除成功')
          this.getPermissionList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑权限点
    editPermission() {
      this.$refs.form.validate(async (isOk) => {
        if (isOk) {
          await updatePermissionService(this.permissionForm)
          this.$message.success('更新权限点成功')
          this.dialogVisible = false
          this.getPermissionList()
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
  .app-container {
    padding: 20px;
  }
}
</style>
